<template>
    <div class="user-management-container">

        <!-- 查询表单 -->
        <el-card class="search-card">
            <el-form :model="queryParams" :inline="true" class="search-form">
                <el-form-item>
                    <el-input v-model="queryParams.keyword" placeholder="请输入用户名" clearable />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select style="width: 140px;" v-model="queryParams.status" placeholder="请选择状态" clearable>
                        <el-option label="启用" value="1" />
                        <el-option label="禁用" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 操作按钮 -->
        <div class="operation-buttons"  v-permission="['editUser']">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>新增用户
            </el-button>
            <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
                <el-icon>
                    <Delete />
                </el-icon>批量删除
            </el-button>
        </div>

        <!-- 用户列表 -->
        <el-card class="table-card">
            <el-table :data="userList" border style="width: 100%" @selection-change="handleSelectionChange"
                v-loading="loading">
                <el-table-column type="selection" width="55" v-permission="['editUser']" />
                <el-table-column label="头像" width="100">
                    <template #default="{ row }">
                        <el-avatar :size="50"
                            :src="row.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" width="120" />
                <el-table-column prop="systemUserName" label="昵称" width="120" />
                <el-table-column prop="roleName" label="角色" width="120" />
                <el-table-column prop="phone" label="手机号" width="150" />
                <el-table-column prop="email" label="邮箱" width="180" />
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                            {{ row.status === '1' ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column v-permission="['editUser']" label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.pageSize"
                :total="total" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 新增/编辑用户对话框 -->
        <user-dialog v-model="dialogVisible" :dialog-title="dialogTitle" :form-data="formData" @submit="handleSubmit" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import UserDialog from './components/UserDialog.vue'
import { getUserList as fetchUserList, updateUser, deleteUser } from '@/api/systemUser'
import { ElMessageBox, ElMessage } from 'element-plus'

// 查询参数
const queryParams = reactive({
    page: 1,
    pageSize: 10,
    keyword: '',
    status: ''
})

// 用户列表数据
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedIds = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref({
    id: '',
    avatar: '',
    username: '',
    systemUserName: '',
    phone: '',
    email: '',
    roleId: '',
    status: '1'
})

// 获取用户列表
const getUserList = async () => {
    loading.value = true
    try {
        const res = await fetchUserList(queryParams)
        userList.value = res.data.list
        total.value = res.data.total
    } catch (error) {
        console.error('获取用户列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 查询
const handleSearch = () => {
    queryParams.page = 1
    getUserList()
}

// 重置查询
const resetSearch = () => {
    queryParams.keyword = ''
    queryParams.status = ''
    handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
    queryParams.pageSize = val
    getUserList()
}

// 当前页改变
const handleCurrentChange = (val) => {
    queryParams.page = val
    getUserList()
}

// 表格选择项改变
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id)
}

// 新增用户
const handleAdd = () => {
    dialogTitle.value = '新增用户'
    formData.value = {
        id: '',
        avatar: '',
        username: '',
        systemUserName: '',
        phone: '',
        email: '',
        roleId: '',
        status: '1'
    }
    dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
    dialogTitle.value = '编辑用户'
    formData.value = { ...row }
    dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm('确认删除该用户吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await deleteUser({ids: row.id})
        ElMessage.success('删除成功')
        await getUserList()
    } catch (error) {
        console.log(error)
        if (error !== 'cancel') {
            console.error('删除用户失败:', error)
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    try {
        await ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}个用户吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await deleteUser({ids: selectedIds.value.join(',')})
        ElMessage.success('批量删除成功')
        await getUserList()
        selectedIds.value = []
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除用户失败:', error)
        }
    }
}

// 提交表单
const handleSubmit = async (formData) => {
    // 这里应该是API调用
    try {
        await updateUser(formData)
        ElMessage.success(`${dialogTitle.value}成功`)
        getUserList()
        dialogVisible.value = false
    } catch (error) {
        console.error('提交失败:', error)
    }

}

// 初始化获取用户列表
onMounted(() => {
    getUserList()
})
</script>

<style scoped>
.user-management-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
}

.operation-buttons {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>
